package com.htc.callcare.datacontroller;

import android.content.Context;
import android.os.Handler;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;

import com.android.internal.telephony.ITelephony;
import com.htc.callcare.database.Database;
import com.htc.callcare.infrastructure.globalVar;

public class Timer extends Thread{
	ITelephony telephonyService;
	String incomeNumber;
	Context context;
	Handler handler;
	public Timer(ITelephony telephonyService, String incomeNumber, Context context){
		this.telephonyService = telephonyService;
		this.incomeNumber = incomeNumber;
		this.context = context;
		handler = new Handler();
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		for (int i = 0; i < globalVar.callTimeout; i++) {
			Log.e("thuutai", "FLAG" + VoiceMailFileController.getTimeout());
			if (!VoiceMailFileController.getTimeout()) {
				try {
					if (!VoiceMailFileController.getTimeout()) {
						Thread.sleep(1000);
						if (i == globalVar.callTimeout - 1) {
							VoiceMailFileController.setTimeOut(true);
							Log.e("thuutai", "Time Out");
							try {
								Database db = new Database(context);
								//If Time out, end Call
								telephonyService.endCall();
								//Add new phone number to DB
								db.addVoiceMailNumber(incomeNumber);
								Log.e("thuutai", "add number to DB");
								//Send Message to notify
								sendCallAgainMessage(incomeNumber);
								//Update that SMS was send
								db.updateSendMessage(incomeNumber, 1);
								Log.e("thuutai", "update that SMS was send");
								//Update that No late for time out
								db.updateTimeOut(incomeNumber, 0);
								Log.e("thuutai", "update that No late for voice mail");
								//Start 1 minute Timer
								OneMinuteTimer oneMinuteTimer =  new OneMinuteTimer(incomeNumber, context);
								oneMinuteTimer.start();
								
							} catch (RemoteException e) {
								e.printStackTrace();
							}
						}

					}

				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			} else {
				Log.e("thuutai", "no time out");
			}
		}
	}

	private void sendCallAgainMessage(final String incomeNumber) {
		Log.v("thuutai", "Send message");
		handler.post(new Runnable() {
			
			@Override
			public void run() {
				Toast.makeText(context, "Send SMS to "+incomeNumber, Toast.LENGTH_SHORT).show();
			}
		});
		
	}
	
}
